package com.example.coursedesign.ui.home.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.coursedesign.R;

import java.util.List;

public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoViewHolder> {

    private final Context context;
    private final List<String> videoPaths; // 视频路径列表
    private final List<Integer> thumbnailIds; // 视频缩略图资源ID列表
    private final List<String> descriptions; // 视频描述列表
    private OnItemClickListener listener;

    public VideoAdapter(Context context, List<String> videoPaths, List<Integer> thumbnailIds, List<String> descriptions) {
        this.context = context;
        this.videoPaths = videoPaths;
        this.thumbnailIds = thumbnailIds;
        this.descriptions = descriptions;
    }

    @NonNull
    @Override
    public VideoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_video, parent, false);
        return new VideoViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull VideoViewHolder holder, int position) {
        // 设置缩略图
        holder.thumbnailImageView.setImageResource(thumbnailIds.get(position));

        // 设置描述文本
        if (descriptions != null && !descriptions.isEmpty() && position < descriptions.size()) {
            holder.descriptionTextView.setText(descriptions.get(position));
        } else {
            holder.descriptionTextView.setText(""); // 设置默认值或空值
        }

        // 设置点击事件以切换播放状态或跳转到详情页
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onItemClick(position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return videoPaths.size();
    }

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    static class VideoViewHolder extends RecyclerView.ViewHolder {
        final ImageView thumbnailImageView;
        final VideoView videoView;
        final ImageView playButton;
        final TextView descriptionTextView;

        VideoViewHolder(@NonNull View itemView) {
            super(itemView);
            thumbnailImageView = itemView.findViewById(R.id.thumbnailImageView);
            videoView = itemView.findViewById(R.id.videoView);
            playButton = itemView.findViewById(R.id.playButton);
            descriptionTextView = itemView.findViewById(R.id.videoTitle);
        }
    }
}